using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MessageHandlers;
using System;
using System.IO;
using System.Text;
using System.Web.Mvc;
namespace Senparc.Weixin.MP.MvcExtension
{
	public class FixWeixinBugWeixinResult : ContentResult
	{
		protected IMessageHandlerDocument _messageHandlerDocument;
		public string Content
		{
			get
			{
				string result;
				if (base.Content != null)
				{
					result = base.Content;
				}
				else
				{
					if (this._messageHandlerDocument != null && this._messageHandlerDocument.TextResponseMessage != null)
					{
						if (this._messageHandlerDocument.ResponseDocument != null)
						{
							result = this._messageHandlerDocument.TextResponseMessage.Replace("\r\n", "\n");
						}
						else
						{
							result = this._messageHandlerDocument.TextResponseMessage;
						}
					}
					else
					{
						result = null;
					}
				}
				return result;
			}
			set
			{
				base.Content = value;
			}
		}
		public FixWeixinBugWeixinResult(IMessageHandlerDocument messageHandlerDocument)
		{
			this._messageHandlerDocument = messageHandlerDocument;
		}
		public FixWeixinBugWeixinResult(string content)
		{
			base.Content = content;
		}
		public override void ExecuteResult(ControllerContext context)
		{
			if (base.Content == null)
			{
				if (this._messageHandlerDocument == null)
				{
					throw new WeixinException("执行WeixinResult时提供的MessageHandler不能为Null！", null);
				}
				if (this._messageHandlerDocument.FinalResponseDocument != null)
				{
					context.HttpContext.Response.ClearContent();
					context.HttpContext.Response.ContentType = "text/xml";
					string s = this._messageHandlerDocument.FinalResponseDocument.ToString().Replace("\r\n", "\n");
					using (new MemoryStream())
					{
						byte[] bytes = Encoding.UTF8.GetBytes(s);
						context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);
					}
				}
			}
		}
	}
}
